package stack;

import java.io.StringReader;
import java.util.Stack;

public class leetcode394 {
    public static void main(String[] args) {
        String s = "2[abc]3[cd]ef";
        System.out.println(decodeString(s));
    }

    public static String decodeString(String s){
        Stack<Integer> countStack = new Stack<>();
        Stack<StringBuilder> stringStack = new Stack<>();
        StringBuilder currentString = new StringBuilder();
        int k = 0;

        for (char ch : s.toCharArray()) {
            if (Character.isDigit(ch)) {
                k = k * 10 + ch - '0';
            } else if (ch == '[') {
                // 将当前计数和字符串压入栈
                countStack.push(k);
                stringStack.push(currentString);
                // 重置当前字符串和计数
                currentString = new StringBuilder();
                k = 0;
            } else if (ch == ']') {
                // 弹出计数和之前的字符串
                StringBuilder decodedString = stringStack.pop();
                int count = countStack.pop();
                // 构建重复的字符串
                for (int i = 0; i < count; i++) {
                    decodedString.append(currentString);
                }
                currentString = decodedString;
            } else {
                currentString.append(ch);
            }
        }

        return currentString.toString();
    }
}
